import PrintJs from './print'

const addEvent = (element, type, callback) => {
  if (element.addEventListener) {
    element.addEventListener(type, callback, false)
  } else if (element.attachEvent) {
    element.attachEvent('on' + type, callback)
  } else {
    element['on' + type] = callback
  }
}

const Print = {
  directiveName: 'print',
  bind(el, binding, vnode) {
    const vue = vnode.context
    let id = ''
    addEvent(el, 'click', () => {
      vue.$nextTick(() => {
        let obj = {}
        if (typeof binding.value === 'string') {
          // 全局打印
          id = binding.value
        } else if (typeof binding.value === 'object' && !!binding.value.id) {
          // 局部打印
          id = binding.value.id
          obj = binding.value
          const ids = id.replace(new RegExp('#', 'g'), '')
          const elsdom = document.getElementById(ids)
          if (!elsdom) {
            console.log('id in Error')
            id = ''
          }
        } else {
          window.print()
          return
        }
        localPrint(obj)
      })
    })

    const localPrint = (options) => {
      new PrintJs({
        id: id, // * 局部打印必传入id
        pageSize: options.pageSize || null, // portrait-纵向打印，landscape-横向打印;默认不设置
        popTitle: binding.value.popTitle // title的标题
      })
    }
  }
}

const install = function(Vue) {
  Vue.directive('Print', Print)
}

if (window.Vue) {
  window['print'] = Print
  Vue.use(install) // eslint-disable-line
}

Print.install = install
export default Print
